import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService } from '../../../common/services/base.service';
import { Role } from '../entities/role.entity';

@Injectable()
export class RoleService extends BaseService<Role> {
  constructor(
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
  ) {
    super(roleRepository);
  }

  /**
   * 获取资源类型名称
   */
  public getResourceType(): string {
    return 'role';
  }

  /**
   * 获取资源名称
   */
  public getResourceName(): string {
    return '角色';
  }

  /**
   * 根据代码查找角色
   */
  async findByCode(code: string): Promise<Role | null> {
    return await this.findOne({ code } as any);
  }

  /**
   * 检查角色代码是否存在
   */
  async isCodeExists(code: string, excludeId?: string): Promise<boolean> {
    const query = this.createQueryBuilder('role')
      .where('role.code = :code', { code })
      .andWhere('role.isDeleted = :isDeleted', { isDeleted: false });

    if (excludeId) {
      query.andWhere('role.id != :excludeId', { excludeId });
    }

    const count = await query.getCount();
    return count > 0;
  }

  /**
   * 创建超级管理员角色
   */
  async createSuperAdminRole(): Promise<Role> {
    const existingRole = await this.findByCode('SUPER_ADMIN');
    if (existingRole) {
      return existingRole;
    }

    const superAdminRole = this.roleRepository.create({
      code: 'SUPER_ADMIN',
      name: '超级管理员',
      description: '系统超级管理员，拥有所有权限',
    });

    return await this.roleRepository.save(superAdminRole);
  }

  /**
   * 获取所有角色（用于下拉选择等）
   */
  async getAllRolesForSelection(): Promise<{ id: string; code: string; name: string }[]> {
    const roles = await this.findAll({
      select: ['id', 'code', 'name'],
      order: { createdAt: 'ASC' },
    });

    return roles.map(role => ({
      id: role.id,
      code: role.code,
      name: role.name,
    }));
  }
}
